const db = require('../db/index.js')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config.js')
exports.regUser = (req, res) => {
    let userInfo = req.body
    if (!userInfo.password || !userInfo.username) {
        return res.cc("请输入用户名和密码")
    }
    // 检测是否被占用
    let sql = "select * from users where username =?"
    db.query(sql, userInfo.username, (err, result) => {
        if (err) {
            return res.cc(err)
        }
        if (result.length > 0) {
            return res.cc('用户名已存在')
        } else {
            // 对密码进行加密
            userInfo.password = bcryptjs.hashSync(userInfo.password, 10)
            let sqlStr = "Insert into users(username,password) values(?,?)"
            db.query(sqlStr, [userInfo.username, userInfo.password], (err2, result) => {
                if (err) {
                    return res.cc(err2)
                }
                res.send({ code: 200, msg: "新增成功" })
            })
        }
    })

}

exports.login = (req, res) => {
    let userInfo = req.body
    if (!userInfo.password || !userInfo.username) {
        return res.cc("请输入用户名和密码")
    }
    console.log(userInfo)
    let sql = "select * from users where username =?"
    db.query(sql, userInfo.username, (err, result) => {
        if (err) {
            return res.cc(err)
        }
        if (result.length === 0) {
            return res.cc("用户名不存在")
        }


        if (!bcryptjs.compareSync(userInfo.password, result[0].password)) {
            return res.cc("密码错误")
        }
        const user = {...result[0],password:''}

        // 对用户信息进行加密，生成token字符串
        const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
        // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NiwidXNlcm5hbWUiOiJ6eWMiLCJwYXNzd29yZCI6IiIsImVtYWlsIjpudWxsLCJuaWNrbmFtZSI6bnVsbCwiaWF0IjoxNzIyMjM2MDI0LCJleHAiOjE3MjIyMzk2MjR9.Z6wL-zMZ6rP5yKn21E73vxhN_lfNeyxwavd5H2hkZQU

        res.send({ code: 200, msg: "登录成功" , token: tokenStr })
    })
}